// https://www.bilibili.com/video/BV1zG4y1z7hB/?spm_id_from=pageDriver&vd_source=d6271710c0aa78f4d90fc3f7028b8301
class Node {
  constructor(value = 0, next = null) {
    this.value = value
    this.next = next
  }
}
function reverse (link) {
  let p = link
  let reverse = null

  while (p !== null) {
    const node = p
    p = p.next
    node.next = reverse
    reverse = node
  }

  return reverse
}

function reverseNMNode (link, n, m) {
  let preN = null
  let N = null
  let M = null
  let afterM = null
  let dunmyLink = new Node(-1, link)
  let curr = dunmyLink
  for (let i = 0; i < n - 1; i++) {
    curr = curr.next
  }
  preN = curr
  N = curr.next
  for (let i = 0; i < m - n + 1; i++) {
    curr = curr.next
  }
  M = curr
  afterM = curr.next
  // 截断
  preN.next = null
  M.next = null
  reverse(N)
  preN.next = M
  N.next = afterM
  return dunmyLink.next
}

// 编码测试
let first = new Node('1')
const second = new Node('2')
const third = new Node('3')
const forth = new Node('4')
const fifth = new Node('5')
first.next = second
second.next = third
third.next = forth
forth.next = fifth
console.log(JSON.stringify(first, null, 2))

reverseNMNode(first, 2, 4) // 翻转2-5位置
console.log(JSON.stringify(first, null, 2))